import Vue from 'vue'
import VueRouter from 'vue-router'
// 配置路由
import login from '../views/user/login.vue'
// 导入主页四个组件
import home from '@/views/home/home.vue'
import movie from '@/views/movie/movie.vue'
import qa from '@/views/qa/qa.vue'
import user from '@/views/user/user.vue'
import layout from '@/views/layout.vue'
import notfound from '@/views/notfound.vue'
import edit from '@/views/user/edit.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import student from '@/views/user/student.vue'

Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name: 'myarticle',
    path: '/article',
    component: article
  },
  {
    name: 'searchResult',
    path: '/searchResult',
    component: searchResult
  },
  {
    name: 'student',
    path: '/student',
    component: student
  },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      {
        name: 'home',
        path: '/home',
        component: home
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        meta: { isLogin: true }
      },
      { path: '/', redirect: '/home' }
    ]
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  { path: '*', redirect: '/notfound' }
]
/* 去掉路由跳转reject异常提示
注意：我们是直接修改VueRouter的原型，所以需要在实例化之前调用
*/
//(1)先保存路由原型链中默认的跳转函数
const originalPush = VueRouter.prototype.push
//(2)替换原型链中的push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 正常执行
    //originalPush.call() : 我们自定义的push底层还是调用默认的push
    return originalPush.call(this, location, onResolve, onReject)
  }
  //如果有异常，本来这个err默认是抛出的，我们直接不做任何处理（给吞掉了）
  /* 
  底层默认是抛出异常：err => {throw err}
  我们不抛出，不做任何处理：err => err
  */
  return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
  routes
})
import { getToken } from '@/utils/token.js'
import { Toast } from 'vant'

/* 注册路由前置导航守卫 */
router.beforeEach((to, from, next) => {
  // ...
  //to: 要跳转的路由 （要到那里去）
  // console.log(to)
  //from : 从哪个路由跳转（从哪里来）
  // console.log(from)
  /*next : ***必须要调用的，否则路由无法跳转*** 
  next() :没有传参。 通过检查 。 允许跳转to页面
  next('/path') :传参数. 没有通过检查 。跳转到指定页面
  */
  /* 并不是所有的页面都需要做登录判断，把需要登录判断的页面添加meta */
  if (to.meta.isLogin) {
    //需要做登录判断
    if (getToken()) {
      //有登录,不拦截，允许正常跳转
      next()
    } else {
      //没登录，进行拦截。 跳转登录页
      //弹窗提示
      Toast.fail('请先登录')
      //跳转登录页
      next('/login')
    }
  } else {
    //不需要做登录判断，无条件跳转
    next()
  }
})

export default router
